const path = require('path');
const Koa = require('koa');
const app = new Koa();
const bodyparser = require('koa-bodyparser');
const Router = require('koa-router');
const router = new Router();
const serve = require('koa-static');
const sqlite = require('sqlite3').verbose();
const sql = require('./sql.js');

const genRes = (data, success, msg) => ({data, success, msg});

app.use(serve(path.join(__dirname,'../dist')));
app.use(bodyparser());
app.use((ctx, next) => {
	ctx.res.setHeader('Access-Control-Allow-Origin', '*');
	ctx.res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
	next();
})
// 保存日记
router.post('/save', async (ctx, next) => {
	const reqData = ctx.request.body;
	// ctx.body = 'sssss'
	if(reqData.id) {
		const s = `UPDATE diary SET 
		title = ${reqData.title} 
		html_content = ${reqData.html_content} 
		markdown_content = ${reqData.markdown_content} 
		updatedAt = '${Date.now()}' 
		WHERE id = ${reqData.id}`;
		sql.run(db, s).then(id => ctx.body = genRes({id}, true))
	} else {
		console.log('hey')
		const s = `INSERT INTO diary(createdAt, updatedAt, title, html_content, markdown_content) VALUES(
		'${Date.now()}', 
		'${Date.now()}', 
		'${reqData.title}', 
		'${reqData.html_content}', 
		'${reqData.markdown_content}')`;
		const id = await sql.run(db, s);
		ctx.body = genRes({id}, true);
		// next();
	}
})
app
  .use(router.routes())
  .use(router.allowedMethods());
app.listen(3000, () => {console.log('server bound..')});

// 数据库连接
const db = new sqlite.Database('./diary.db');
db.run('PRAGMA foreign_keys = ON');

